package com.tarena.luban.demo.gateway.filters;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class AuthenticationFilterDemo implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取参数 没带 token没值 有值格式不对 正确
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        List<String> token = queryParams.get("token");
        String message=null;
        if (CollectionUtils.isEmpty(token)){
            //token没携带
            message="请求没有携带token";
        }
        if (message!=null){
            //输出响应
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            return exchange.getResponse().
                    writeWith(Mono.fromSupplier(
                            ()->exchange.getResponse().bufferFactory().wrap(bytes)));
        }
        String tokenValue = token.get(0);
        if (StringUtils.isEmpty(tokenValue)){
            //token值为空
            message="您的token没有值";
        }
        if (message!=null){
            //输出响应
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            return exchange.getResponse().
                    writeWith(Mono.fromSupplier(
                            ()->exchange.getResponse().bufferFactory().wrap(bytes)));
        }
        //正则判断
        boolean match=tokenValue.matches("\\d{10}");
        if (!match){
            message="您的token值格式不正确";
        }
        if (message!=null){
            //输出响应
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            return exchange.getResponse().
                    writeWith(Mono.fromSupplier(
                            ()->exchange.getResponse().bufferFactory().wrap(bytes)));
        }
        return chain.filter(exchange);
    }
}
